package learn.algorithm.train;

public class Code2022010501_SumOfFactorial {
  // 这种求阶乘和的方法相对于f2低效
  public static long f1(int N) {
    long sum = 0;
    for (int j = 1; j <= N; j++) {
      sum = sum + factorial(j);
    }
    return sum;
  }

  public static long factorial(int N) {
    long ans = 1;
    for (int i = 1; i <= N; i++) {
      ans = ans * i;
    }
    return ans;
  }

  /**
   * 这种效率高一些，是因为缓存了前一次计算的结果
   * @param N
   * @return
   */
  public static long f2(int N) {
    long sum = 0;
    long pre = 1;
    for (int i = 1; i <= N; i++) {
      pre = pre * i;
      sum = sum + pre;
    }
    return sum;
  }

  public static void main(String[] args) {
    for (int i = 1; i <= 20; i++) {
      System.out.println("f1计算得到的值" + f1(i) + "     " +"f2计算得到的值:" + f2(i));
    }
  }

}
